package com.kbbywyclient.ui.activity;

import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.kbbywyclient.R;
import com.kbbywyclient.data.entity.Event;
import com.kbbywyclient.data.entity.LoansTableMenu;
import com.kbbywyclient.data.entity.MyProduct;
import com.kbbywyclient.data.entity.ProductLib;
import com.kbbywyclient.data.model.base.BaseModel;
import com.kbbywyclient.di.AppComponent;
import com.kbbywyclient.di.module.ProductManageModule;
import com.kbbywyclient.presenter.ProductManagePresenter;
import com.kbbywyclient.ui.activity.base.BaseActivity;
import com.kbbywyclient.ui.adapter.MyProductStatueLvAdapter;
import com.kbbywyclient.ui.adapter.ProductLibAdapter;
import com.kbbywyclient.ui.adapter.ProductLibStatueLvAdapter;
import com.kbbywyclient.ui.adapter.ProductManageMyAdapter;
import com.kbbywyclient.ui.adapter.ViewPagerAdapter;
import com.kbbywyclient.ui.adapter.decoration.ListViewDecoration;
import com.kbbywyclient.ui.contarct.ProductManageContract;
import com.kbbywyclient.util.ActivitySkipUtil;
import com.kbbywyclient.util.StringUtil;
import com.kbbywyclient.util.ToastUtil;
import com.kbbywyclient.util.ViewUtils;
import com.kbbywyclient.util.pre.PreUtils;
import com.kbbywyclient.widget.CustomPopwin;
import com.kbbywyclient.widget.CustomToolBar;
import com.kbbywyclient.widget.NoScrollViewPager;
import com.ogaclejapan.smarttablayout.SmartTabLayout;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Description:
 * Created by FHW
 * on 2017/5/10
 */

public class ProductManageActivity extends BaseActivity implements ProductManageContract.View {

    @BindView(R.id.v_toolbar)
    CustomToolBar v_toolbar;
    @BindView(R.id.stb_viewpagertab)
    SmartTabLayout stb_viewpagertab;
    @BindView(R.id.vp_viewpager)
    NoScrollViewPager vp_viewpager;

    @BindView(R.id.ll_top)
    LinearLayout ll_top;
    @BindView(R.id.et_keyword)
    EditText et_keyword;
    @BindView(R.id.tv_screen)
    TextView tv_screen;
    @BindView(R.id.tv_look_up)
    TextView tv_look_up;


    private ViewPagerAdapter pagerAdapter;
    private List viewContainter;
    private ArrayList<String> titles;
    private int mType = 0;//0 -我的产品   1-产品库

    private String isVerified = "";
    private String parentUsage = "";
    private String screen_my = "产品状态";
    private String screen_lib = "贷款用途";

    private String keWord = "";

    @Inject
    ProductManagePresenter productManagePresenter;

    //我的产品
    private List<MyProduct> myProductList = null;
    private ProductManageMyAdapter productManageMyAdapter = null;
    private SwipeRefreshLayout swipe_layout;
    private SwipeMenuRecyclerView lv_my_product;
    private boolean isFristLoadMy = false;
    private boolean isMore = true;

    private CustomPopwin popMy;
    private MyProductStatueLvAdapter myProductStatueLvAdapter;
    private List<String> strMyList;
    private int myPosition = 0;

    //产品库
    private List<ProductLib> productLibList = null;
    private ProductLibAdapter productLibAdapter;
    private boolean isFristLoadLib = true;
    private SwipeRefreshLayout swipe_layout_lib;
    private SwipeMenuRecyclerView lv_product_lib;
    private boolean isMore_lib = true;

    private CustomPopwin popLib;
    private ArrayList<LoansTableMenu.LoansTypeBean> loansTypeList;
    private ProductLibStatueLvAdapter productLibStatueLvAdapter;


    @Override
    protected int provideContentViewId() {
        return R.layout.activity_product_manage;
    }

    @OnClick({R.id.tv_look_up, R.id.tv_screen})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_look_up://查找
                if (StringUtil.isNotEmpty(keWord)) {
                    switch (mType) {
                        case 0:
                            swipe_layout.setRefreshing(true);
                            refreshAll(true);
                            break;
                        case 1:
                            swipe_layout_lib.setRefreshing(true);
                            refreshLib(true);
                            break;
                    }
                } else {
                    ToastUtil.showShort("请输入要需要查找的产品名称");
                }
                break;
            case R.id.tv_screen:
                switch (mType) {
                    case 0:
                        showPopMy(ll_top);
                        break;
                    case 1:
                        showPopLib(ll_top);
                        break;
                }
                break;
        }
    }

    private void showPopLib(View view) {
        View proView = LayoutInflater.from(this).inflate(R.layout.pop_my_product_statue, null, false);

        ListView lv_area = (ListView) proView.findViewById(R.id.lv_area);

        productLibStatueLvAdapter = new ProductLibStatueLvAdapter(this, R.layout.item_address_procince, loansTypeList);
        lv_area.setAdapter(productLibStatueLvAdapter);

        if (popLib == null) {
            popLib = new CustomPopwin(this);
        }
        popLib.setContentView(proView);
//        popLib.showAsDropDown(view, -262, 0, Gravity.RIGHT);
        popLib.showAsDropDown(view, -(tv_look_up.getWidth() * 2 - 46), 0, Gravity.RIGHT);
        lv_area.setOnItemClickListener((parent, view1, position1, id) -> {
            screen_lib = loansTypeList.get(position1).getName();
            parentUsage = loansTypeList.get(position1).getCode() + "";
            ViewUtils.setText(tv_screen, screen_lib);
            swipe_layout_lib.setRefreshing(true);
            refreshLib(true);

            popLib.dismiss();
        });
    }

    /**
     * 选择 产品状态
     *
     * @param view
     */
    private void showPopMy(View view) {
        View proView = LayoutInflater.from(this).inflate(R.layout.pop_my_product_statue, null, false);

        ListView lv_area = (ListView) proView.findViewById(R.id.lv_area);

        myProductStatueLvAdapter = new MyProductStatueLvAdapter(this, R.layout.item_address_procince, strMyList);
        lv_area.setAdapter(myProductStatueLvAdapter);

        if (popMy == null) {
            popMy = new CustomPopwin(this);
        }
        popMy.setContentView(proView);
//        popMy.showAsDropDown(view, -262, 0, Gravity.LEFT);
        popMy.showAsDropDown(view, -(tv_look_up.getWidth() * 2 - 46), 0, Gravity.RIGHT);
        lv_area.setOnItemClickListener((parent, view1, position1, id) -> {
            screen_my = strMyList.get(position1);
            switch (position1) {
                case 0:
                    isVerified = "";
                    break;
                case 1:
                    isVerified = "0";
                    break;
                case 2:
                    isVerified = "1";
                    break;
                case 3:
                    isVerified = "2";
                    break;
            }
            ViewUtils.setText(tv_screen, screen_my);

            swipe_layout.setRefreshing(true);
            refreshAll(true);

            popMy.dismiss();
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        setScreenName("产品管理");
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        myProductList = new ArrayList<>();
        strMyList = new ArrayList<>();
        strMyList.add("不限");
        strMyList.add("待审");
        strMyList.add("通过");
        strMyList.add("不通过");

        productLibList = new ArrayList<>();
        loansTypeList = new ArrayList<>();

        v_toolbar.setLeftViewOnClickLinster(v -> finish());
        v_toolbar.setRightViewOnClickLinster(v -> {
            ActivitySkipUtil.skipAnotherActivity(this, AddProductActivity.class);
        });
        et_keyword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                keWord = s.toString();
            }
        });


        setViewPager();
        stb_viewpagertab.setViewPager(vp_viewpager);
        stb_viewpagertab.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mType = position;
                switch (position) {
                    case 0://我的产品
                        ViewUtils.setText(tv_screen, screen_my);
                        break;
                    case 1://产品库
                        ViewUtils.setText(tv_screen, screen_lib);
                        if (isFristLoadLib) {
                            refreshLib(true);
                        }
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    private void setViewPager() {
        viewContainter = new ArrayList<>();
        titles = new ArrayList<>();
        titles.add("我的产品");
        titles.add("产品库");

        View view = LayoutInflater.from(this).inflate(R.layout.vp_my_product, null);

        swipe_layout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_layout);
        lv_my_product = (SwipeMenuRecyclerView) view.findViewById(R.id.lv_my_product);

        swipe_layout.setOnRefreshListener(() -> {
            swipe_layout.setRefreshing(true);
            refreshAll(true);
        });
        setViewListener(lv_my_product);
        // viewpager开始添加view
        viewContainter.add(view);

        View view1 = LayoutInflater.from(this).inflate(R.layout.vp_product_library, null);

        swipe_layout_lib = (SwipeRefreshLayout) view1.findViewById(R.id.swipe_layout_lib);
        lv_product_lib = (SwipeMenuRecyclerView) view1.findViewById(R.id.lv_product_lib);

        swipe_layout_lib.setOnRefreshListener(() -> {
            swipe_layout_lib.setRefreshing(true);
            refreshLib(true);
        });
        setViewListener(lv_product_lib);
        // viewpager开始添加view
        viewContainter.add(view1);

        // 设置适配器
        pagerAdapter = new ViewPagerAdapter(viewContainter, titles);
        vp_viewpager.setAdapter(pagerAdapter);

    }

    private void setViewListener(SwipeMenuRecyclerView lv) {
        lv.setLayoutManager(new LinearLayoutManager(this));// 布局管理器。
        lv.setHasFixedSize(true);// 如果Item够简单，高度是确定的，打开FixSize将提高性能。
        lv.setItemAnimator(new DefaultItemAnimator());// 设置Item默认动画，加也行，不加也行。
        lv.addItemDecoration(new ListViewDecoration());// 添加分割线。
        // 添加滚动监听。
        lv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                if (!recyclerView.canScrollVertically(1)) {// 手指不能向上滑动了
                    switch (mType) {
                        case 0:
                            if (isMore) {
                                refreshAll(false);
                            } else {
                                if (myProductList.size() > 5) {
                                    ToastUtil.showShort("没有更多了");
                                }
                            }
                            break;
                        case 1:
                            if (isMore_lib) {
                                refreshLib(false);
                            } else {
                                if (productLibList.size() > 5) {
                                    ToastUtil.showShort("没有更多了");
                                }
                            }
                            break;
                    }
                }
            }
        });
        // 设置菜单创建器。
        lv.setSwipeMenuCreator(swipeMenuCreator);
        // 设置菜单Item点击监听。
        lv.setSwipeMenuItemClickListener((closeable, adapterPosition, menuPosition, direction) -> {
            switch (menuPosition) {
                case 0:
                    HashMap<String, Object> map = new HashMap<>();
                    switch (mType) {
                        case 0:
                            map.put("productLoansID", myProductList.get(adapterPosition).getProductLoansID() + "");
                            break;
                        case 1:
                            map.put("productLoansID", productLibList.get(adapterPosition).getID() + "");
                            break;
                    }
                    map.put("mType", mType);
                    ActivitySkipUtil.skipAnotherActivity(this, ErrorCorrectionActivity.class, map);
                    break;
                case 1:
                    switch (mType) {
                        case 0:
                            myPosition = adapterPosition;
                            productManagePresenter.getMyDel(PreUtils.getUser(this).getSalesID() + ""
                                    , myProductList.get(adapterPosition).getProductLoansID() + "");
                            break;
                        case 1:
                            productManagePresenter.getProductAdd(PreUtils.getUser(this).getSalesID() + "", productLibList.get(adapterPosition).getID() + "");
                            break;
                    }
                    break;
            }
            lv.smoothCloseMenu();
        });
    }

    /**
     * 菜单创建器。在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = (swipeLeftMenu, swipeRightMenu, viewType) -> {
        int width = getResources().getDimensionPixelSize(R.dimen.item_height);

        // MATCH_PARENT 自适应高度，保持和内容一样高；也可以指定菜单具体高度，也可以用WRAP_CONTENT。
        int height = ViewGroup.LayoutParams.MATCH_PARENT;

        // 添加右侧的，如果不添加，则右侧不会出现菜单。
        {
            SwipeMenuItem deleteItem = new SwipeMenuItem(ProductManageActivity.this)
                    .setBackgroundDrawable(R.drawable.selector_dddddd)
                    .setImage(R.mipmap.icon_menu_modify)
                    .setWidth(width)
                    .setHeight(height);
            swipeRightMenu.addMenuItem(deleteItem);// 添加一个按钮到右侧侧菜单。

            SwipeMenuItem closeItem = new SwipeMenuItem(ProductManageActivity.this)
                    .setBackgroundDrawable(R.drawable.selector_fe1211)
                    .setWidth(width)
                    .setHeight(height);
            switch (mType) {
                case 0:
                    closeItem.setImage(R.mipmap.icon_menu_del);
                    break;
                case 1:
                    closeItem.setImage(R.mipmap.icon_product_add);
                    break;
            }
            swipeRightMenu.addMenuItem(closeItem); // 添加一个按钮到右侧菜单。

        }
    };


    @Override
    public void initData() {
        swipe_layout.setRefreshing(true);
        refreshAll(true);
    }

    @Override
    public void initAppComponent(AppComponent appComponent) {
        appComponent.getProductManageComponent(new ProductManageModule(this)).inject(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 我的产品 推荐 回调
     *
     * @param myProductRecomm
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Event.MyProductRecomm myProductRecomm) {
        int position = myProductRecomm.getPosition();
        String recommd = "";
        switch (myProductList.get(position).getRecommend()) {
            case 0:
                recommd = "1";
                break;
            case 1:
                recommd = "0";
                break;
        }
        productManagePresenter.getMyRecommend(PreUtils.getUser(this).getSalesID() + ""
                , myProductList.get(position).getProductLoansID() + "", recommd);
    }

    /**
     * 刷新 我的产品 数据
     *
     * @param isClean
     */
    private void refreshAll(boolean isClean) {
        if (isClean) {
            isMore = true;
        }
        productManagePresenter.getMyproductList(isClean, PreUtils.getUser(this).getSalesID() + "", isVerified, keWord);
    }

    /**
     * 刷新 产品库 数据
     *
     * @param isClean
     */
    private void refreshLib(boolean isClean) {
        if (isClean) {
            isMore_lib = true;
        }
        productManagePresenter.getProductLib(isClean, PreUtils.getUser(this).getSalesID() + "", parentUsage, keWord);
    }

    @Override
    public void showLoadingDialog(String s) {
        showProgress(s);
    }

    @Override
    public void closeLoadingDialog() {
        dismissProgress();
    }

    ///////////////////////////////////////////////////////我的产品/////////////////////////////////
    @Override
    public void loadSucMyproduct(List<MyProduct> myProductList) {
        swipe_layout.setRefreshing(false);
    }

    @Override
    public void loadFaiMyproduct(String errorMsg) {
        swipe_layout.setRefreshing(false);
    }

    @Override
    public void setAdapterOrNotify(List<MyProduct> mMyProductList) {
        if (myProductList.size() > 0) {
            myProductList.clear();
        }
        myProductList.addAll(mMyProductList);
        if (productManageMyAdapter == null) {
            productManageMyAdapter = new ProductManageMyAdapter(myProductList, this);
            lv_my_product.setAdapter(productManageMyAdapter);
        } else {
            productManageMyAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void setNoMore() {
        swipe_layout.setRefreshing(false);
        isMore = false;
    }

    @Override
    public void setMoreComplete() {
        swipe_layout.setRefreshing(false);
    }

    @Override
    public void loadSucMyRecommend(BaseModel baseModel) {
        Map<String, String> o = (Map) baseModel.getData();
        ToastUtil.showShort(o.get("ModifyInfo"));
        swipe_layout.setRefreshing(true);
        refreshAll(true);
    }

    @Override
    public void loadFaiMyRecommend(String errorMsg) {

    }

    @Override
    public void loadSucMyDel(BaseModel baseModel) {
        ToastUtil.showShort("删除成功");
        if (myProductList.size() > 0) {
            myProductList.remove(myPosition);
            productManageMyAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void loadFaiMyDel(String errorMsg) {

    }

///////////////////////////////////////////////////////产品库/////////////////////////////////


    @Override
    public void loadSucProductLib(List<ProductLib> productLibList) {
        swipe_layout_lib.setRefreshing(false);
        if (isFristLoadLib) {
            isFristLoadLib = false;
            productManagePresenter.getloansOrdersMenu(PreUtils.getUser(this).getSalesID() + "");
        }
    }

    @Override
    public void loadFaiProductLib(String errorMsg) {
        swipe_layout_lib.setRefreshing(false);
    }

    @Override
    public void setAdapterOrNotifyLib(List<ProductLib> mProductLibList) {
        if (productLibList.size() > 0) {
            productLibList.clear();
        }
        productLibList.addAll(mProductLibList);
        if (productLibAdapter == null) {
            productLibAdapter = new ProductLibAdapter(productLibList, this);
            lv_product_lib.setAdapter(productLibAdapter);
        } else {
            productLibAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void setNoMoreLib() {
        swipe_layout_lib.setRefreshing(false);
        isMore_lib = false;
    }

    @Override
    public void setMoreCompleteLib() {
        swipe_layout_lib.setRefreshing(false);
    }

    @Override
    public void loadSucMenu(LoansTableMenu loansTableMenu) {
        loansTypeList.addAll(loansTableMenu.getLoansType());
        LoansTableMenu.LoansTypeBean loansTypeBean = new LoansTableMenu.LoansTypeBean();
        loansTypeBean.setName("不限");
        loansTypeBean.setCode("");
        loansTypeList.add(0, loansTypeBean);

    }

    @Override
    public void loadFaiMenu(String errorMsg) {

    }

    @Override
    public void loadSucAdd(BaseModel baseModel) {
        ToastUtil.showShort("添加成功");
    }

    @Override
    public void loadFaiMyAdd(String errorMsg) {

    }

}
